#!/usr/bin/env python

import optparse
import os.path

import histogram

class BadCommandLineError(Exception):
    def __init__(self, msg, code):
        super(BadCommandLineError, self).__init__(msg)
        self.msg = msg
        self.retcode = code

    def __str__(self):
        return self.msg


def main():
    '''
    Usage: %prog [opts] file.hpt
    
    Convert histograms in `file.hpt' into MND (mn_fit native) format.
    '''

    op = optparse.OptionParser(usage=main.__doc__)

    op.add_option("-n", "--name", dest='names', action='append', default=[],
                  help='Write out histogram NAME (can be repeated)',
                  metavar='NAME')    
    op.add_option("-o", "--output", dest='output', default=None, 
                  help='Leave output in PATH', metavar='PATH')

    opts, args = op.parse_args()

    if len(args) < 1:
        msg = "Please supply at least one HPT file to convert"
        raise BadCommandLineError(msg, -1)

    hc = histogram.load(args[0], opts.names)

    if opts.output is None:
        outpath = os.path.basename(args[0]).rsplit('.', 1)[0] + '.mnd'    
    elif opts.output[-4:] != '.mnd':
        opts.output += '.mnd'

    histogram.dump(hc, opts.output)

    return 0


if __name__ == '__main__':
    try:
        import sys
        sys.exit(main())
    except BadCommandLineError, e:
        import os
        sys.stderr.write(str(e) + "\n")
        sys.stderr.write("See `{0} -h' for more.\n".format(
                os.path.basename(sys.argv[0])))
        sys.stderr.flush()
        sys.exit(e.retcode)
            
